package com.jxinternet.platform.services;

import com.jxinternet.platform.services.handler.CustomProtobufDecoder;
import com.jxinternet.platform.services.handler.CustomProtobufEncoder;
import com.jxinternet.platform.services.handler.IdleServerHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("serverChannelInitializer")
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
	private final static int READER_IDLE_TIME_SECONDS = 20;//读操作空闲20秒
	private final static int WRITER_IDLE_TIME_SECONDS = 20;//写操作空闲20秒
	private final static int ALL_IDLE_TIME_SECONDS = 40;//读写全部空闲40秒
	

    @Autowired
    @Qualifier("protoBufServerHandler")
    private ChannelInboundHandlerAdapter protoBufServerHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
    	ChannelPipeline p = socketChannel.pipeline();
    	
    	p.addLast("idleStateHandler", new IdleStateHandler(READER_IDLE_TIME_SECONDS
    			, WRITER_IDLE_TIME_SECONDS, ALL_IDLE_TIME_SECONDS, TimeUnit.SECONDS));
	    p.addLast("idleTimeoutHandler", new IdleServerHandler());

        p.addLast("decode", new CustomProtobufDecoder());//解码方法
        p.addLast("encode", new CustomProtobufEncoder());//编码方法
        p.addLast("protoBufServerHandler", protoBufServerHandler);
    }
}
